#include "list.h"
#include <iostream>

struct list *Create_Head(void)
{
    struct list *head = (struct list *)calloc(1, sizeof(struct list));
    if (head == NULL)
    {
        perror("error");
        return NULL;
    }
    head->id = 0;
    head->next = head;
    head->prev = head;
    std::cout << __LINE__ << std::endl;
    return head;
}

static struct list *Add_Node(void *arg)
{
    return NULL;
}

struct list *Add_End_Node(struct list *head)
{
    struct list *node = (struct list *)calloc(1, sizeof(struct list));
    if (node == NULL)
    {
        perror("error");
        return NULL;
    }
    head->prev->next = node;
    node->next = head;
    node->prev = head->prev;
    head->prev = node;

    return node;
}

struct list *Add_Start_Node(struct list *head)
{
    struct list *node = (struct list *)calloc(1, sizeof(struct list));
    if (node == NULL)
    {
        perror("error");
        return NULL;
    }
    head->next->prev = node;
    node->next = head->next;
    node->prev = head;
    head->next = node;
    return node;
}

void Destroy_Node(struct list *head)
{
    if(head == NULL) return;
    struct list *tmp = head->next;
    struct list *p = NULL; 
    while(tmp != head)
    {
        p = tmp;
        tmp = tmp->next;
        free(p);
    }
    free(head);
}

void Display_Node(struct list *head)
{
    if(head == NULL) return;
    struct list *tmp = head->next;
    struct list *p = NULL;
    while(tmp != head)
    {
        std::cout << "id: "<<tmp->id << std::endl;
        tmp = tmp->next;
    }
}

#if 0
struct list *Add_Node_Func(struct list *head, struct list *node, int position)
{
    if (node == NULL)
    {
        printf("错误：插入的节点为空。\n");
        return head;
    }

    if (head == NULL)
    {
        // 如果链表为空，新节点成为头节点
        head = node;
        node->prev = NULL;
        node->next = NULL;
        return head;
    }

    if (position == 0)
    {
        // 头插
        node->next = head;
        node->prev = NULL;
        head->prev = node;
        head = node;
    }
    else if (position == 1)
    {
        // 尾插
        list *temp = head;
        while (temp->next != NULL)
        {
            temp = temp->next;
        }
        temp->next = node;
        node->prev = temp;
        node->next = NULL;
    }
    else
    {
        printf("错误：未知的插入位置。\n");
    }

    return head;
}
#endif